package com.jielin.handling.service.record.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.jielin.handling.entity.material.Node;
import com.jielin.handling.entity.record.RecordAnswer;
import com.jielin.handling.entity.record.RecordCommonalityModel;
import com.jielin.handling.entity.record.RecordCommonalityVo;
import com.jielin.handling.entity.record.RecordQuestion;
import com.jielin.handling.mapper.record.RecordAnswerMapper;
import com.jielin.handling.mapper.record.RecordCommonalityModelMapper;
import com.jielin.handling.mapper.record.RecordQuestionMapper;
import com.jielin.handling.service.record.RecordQuestionService;
import com.jielin.handling.util.StringUtil;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class RecordQuestionServiceimpl implements RecordQuestionService {
    @Autowired
    private RecordQuestionMapper recordQuestionMapper;
    @Autowired
    private RecordAnswerMapper recordAnswerMapper;
    @Autowired
    private RecordCommonalityModelMapper recordCommonalityModelMapper;

    @Override
    public List<RecordQuestion> findQuestionByModelId(String modelid) {
        if (StringUtil.isEmpty(modelid)) {
            return null;
        }
        List<RecordQuestion> rqList = recordQuestionMapper.findQuestionByModelId(modelid);
        if (rqList.size() > 0) {
            for (RecordQuestion rq : rqList) {
                rq.setAnswer(recordAnswerMapper.findAnswerByQuestionId(rq.getId()));
            }
        }
        return rqList;
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public int addMyModelQuestionAndAnswer(String modelId, String context) {
        log.info("RecordQuestionServiceimpl事务==>addMyModelQuestionAndAnswer()start...");
        int calli = -1;
        try {
            calli = addQuestionAndAnswer(modelId, context);// 处理字符并添加到数据库
        } catch (Exception e) {
            calli = -1;
            log.info("RecordDetailedService 事务回滚:{}", e);
            // 抛出异常让其回滚
            throw new RuntimeException("事务回滚");
        }
        log.info("RecordQuestionServiceimpl事务==>addMyModelQuestionAndAnswer()end...");
        return calli;
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public int updMyModelQuestionAndAnswer(String modelId, String context, String policeId) {
        String trueUserId = recordCommonalityModelMapper.findModelPoliceIdByModelId(modelId);
        if (!StringUtil.isEmpty(trueUserId)) {
            if (!trueUserId.equals(policeId)) {
                return -2;
            }
        }
        log.info("RecordQuestionServiceimpl事务==>updMyModelQuestionAndAnswer()start...");
        int calli = -1;
        try {
            List<String> listQuestionId = recordQuestionMapper.findQuestionIdByModelId(modelId);
            if (listQuestionId.size() > 0) {// 先删除之前存在的问与答
                recordQuestionMapper.delByModelId(modelId);
                recordAnswerMapper.delByQuestionId(listQuestionId);
            }
            calli = addQuestionAndAnswer(modelId, context);// 处理字符并添加到数据库
        } catch (Exception e) {
            calli = -1;
            log.info("RecordDetailedService 事务回滚:{}", e);
            // 抛出异常让其回滚
            throw new RuntimeException("事务回滚");
        }
        log.info("RecordQuestionServiceimpl事务==>updMyModelQuestionAndAnswer()end...");
        return calli;
    }

    private int addQuestionAndAnswer(String modelId, String context) {
        if (StringUtil.isEmpty(modelId) || StringUtil.isEmpty(context)) {
            return -1;
        }
        context = context.replaceAll("\r|\n|\t", "");
        context = context.replace("</p>", "");
        // context = context.replace("<p class=\"qa-item a-item\">", "");
        String[] strs = context.split("<p class=\"qa-item q-item\">");
        List<Node> questionlist = new ArrayList<>();// 问题集合
        List<Node> answerlist = null;// 答案集合
        Node questionNode = null;
        Node answerNode = null;
        for (int i = 0; i < strs.length; i++) {// 截取所有问题
            String row = strs[i];
            if (StringUtil.isEmpty(row)) {
                continue;
            }
            int i1 = row.indexOf("<");
            String one1 = row.substring(0, i1 < 0 ? row.length() : i1);// 问：xxxxxx
            String trueone1 = one1.substring((one1.indexOf("：") + 1), one1.length());// xxxxxx
            String two1 = row.substring(i1, row.length());// <p class="qa-item a-item"> 答:xxxxxxxx <p class="qa-item
            // a-item"> 答:xxxxxxxx

            questionNode = new Node();
            questionNode.setId(StringUtil.generatorUUID());
            questionNode.setText(trueone1);

            answerlist = new ArrayList<>();
            String[] strsChild = two1.split("<p class=\"qa-item a-item\">");
            for (int j = 0; j < strsChild.length; j++) {// 截取所有答案
                String row2 = strsChild[j];
                if (StringUtil.isEmpty(row2)) {
                    continue;
                }
                // String two2 = row.substring(0, i1 + 1);// 答：xxxxxx
                String truetwo2 = row2.substring((row2.indexOf("：") + 1), row2.length());// xxxxxx
                answerNode = new Node();
                answerNode.setId(StringUtil.generatorUUID());
                answerNode.setParentId(questionNode.getId());
                answerNode.setText(truetwo2);
                answerlist.add(answerNode);

            }
            questionNode.setChildren(answerlist);
            questionlist.add(questionNode);
        }
        RecordQuestion rq = null;
        for (int i = 0; i < questionlist.size(); i++) {
            rq = new RecordQuestion();
            rq.setId(questionlist.get(i).getId());
            rq.setModelid(modelId);
            rq.setQuestion(questionlist.get(i).getText());
            rq.setSort(i + 1);
            recordQuestionMapper.addQuestionByModelId(rq);

            List<Node> trueanswerlist = questionlist.get(i).getChildren();
            RecordAnswer ra = null;
            for (int j = 0; j < trueanswerlist.size(); j++) {
                ra = new RecordAnswer();
                ra.setId(trueanswerlist.get(j).getId());
                ra.setQuestionid(trueanswerlist.get(j).getParentId());
                ra.setAnswer(trueanswerlist.get(j).getText());
                recordAnswerMapper.addAnswerByQuestionId(ra);
            }

        }
        return 1;
    }

    @Override
    public List<RecordCommonalityModel> findRecordByAll(String modelId, String modelName, String keyWord,
                                                        String policeId) {
        List<RecordCommonalityVo> rcvList = recordCommonalityModelMapper.findRecordByAll(modelId,
                StringUtil.escapeMysqlChars(modelName), StringUtil.escapeMysqlChars(keyWord),
                policeId);
        if (rcvList.size() == 0) {
            return null;
        }
        List<RecordCommonalityModel> rcmList = null;
        RecordCommonalityModel rcModel = null;
        List<RecordQuestion> rQuestionList = null;
        RecordQuestion rQuestion = null;
        HashMap<String, RecordCommonalityVo> rcmMap = new HashMap<String, RecordCommonalityVo>();// 根据笔录类型id筛选
        HashMap<String, RecordCommonalityVo> rqMap = new HashMap<String, RecordCommonalityVo>();// 根据问题id筛选
        for (RecordCommonalityVo rcv : rcvList) {
            rcmMap.put(rcv.getRcmIds(), rcv);
            if (!StringUtil.isEmpty(rcv.getRqIds())) {
                rqMap.put(rcv.getRqIds(), rcv);
            }
        }

        rcmList = new ArrayList<>(rcmMap.size());// 设置模板类型集合大小

        for (RecordCommonalityVo entry : rcmMap.values()) {
            rcModel = new RecordCommonalityModel();
            rcModel.setId(entry.getRcmIds());
            rcModel.setModeltypeid(entry.getModelTypeId());
            rcModel.setModelname(entry.getRcmNames());
            rQuestionList = new ArrayList<>();// 设置问题集合大小
            for (RecordCommonalityVo rcv : rqMap.values()) {
                if (rcv.getRcmIds().equals(rcModel.getId())) {
                    rQuestion = new RecordQuestion();
                    rQuestion.setId(rcv.getRqIds());
                    rQuestion.setQuestion(rcv.getRqQuestions());
                    rQuestion.setAnswer(recordAnswerMapper.findAnswerByQuestionId(rQuestion.getId()));
                    rQuestionList.add(rQuestion);
                }
            }
            rcModel.setRqList(rQuestionList);
            rcmList.add(rcModel);
        }
        return rcmList;
    }

}
